// 目标：App-useRef-useImperativeHandle真实案例--检验&重置表单组件

import { Button, Input } from 'antd';
import React, { useImperativeHandle, useRef, useState } from 'react';

interface Form {
  username: string;
  password: string;
  email: string;
}

interface ChildRef {
  name: string;
  form: Form;
  validate: () => void;
  reset: () => void;
}

const Child = React.forwardRef<ChildRef>((props, ref) => {
  const [form, setForm] = useState({
    username: '',
    password: '',
    email: '',
  });
  const validate = () => {
    // console.log('校验子组件');
    if (form.username === '' || form.password === '' || form.email === '') {
      return '请填写完整';
    }
    return true;
  };
  const reset = () => {
    console.log('重置子组件');
    setForm({ username: '', password: '', email: '' });
  };
  useImperativeHandle(ref, () => {
    return {
      name: 'form',
      form,
      validate,
      reset,
    };
  });

  return (
    <div>
      <form action="">
        <Input
          placeholder="用户名"
          value={form.username}
          onChange={(e) => {
            setForm({ ...form, username: e.target.value });
          }}
        />
        <Input
          placeholder="密码"
          value={form.password}
          onChange={(e) => {
            setForm({ ...form, password: e.target.value });
          }}
        />
        <Input
          value={form.email}
          placeholder="邮箱"
          onChange={(e) => {
            setForm({ ...form, email: e.target.value });
          }}
        />
      </form>
    </div>
  );
});

const App = () => {
  const childRef = useRef<ChildRef>(null);
  const getFormData = () => {
    console.log(childRef.current?.form);
  };
  return (
    <>
      <div>
        <Child ref={childRef} />
        <Button onClick={() => console.log(childRef.current?.validate())}>校验子组件</Button>
        <Button onClick={() => childRef.current?.reset()}>重置子组件</Button>
        <Button onClick={getFormData}>提交</Button>
      </div>
    </>
  );
};

export default App;

// 步骤：
// 1.确定子组件的内容：form，validate()，reset()
// 2.编写子组件，使用React.forwardRef(() => {})
// 3.暴露子组件，使用useImperativeHandle(ref, createHandle, dependencies?)
// 4.createHandle return一个对象，对象中是要传递给父组件内容 { name, 状态, 方法 }
// 5.补充子组件的类型（自定义泛型类型）。有哪些key，就看要传递给父组件哪些内容。子组件函数补充组件的类型：React.forwardRef<ChildRef>()
// 6.编写父组件。编写UI。
// 7.使用子组件:
//   7-1.useRef定义ref属性值  const childRef = useRef<ChildRef>(null);
//   7-2.子组件ref属性绑定 <Child ref={childRef} />
// 8.父组件调用子组件方法：childRef.current?.xxx

// 注意：
// 1.学会定义ChildRef类型
// 2.关注基础知识 onChange={(e) => {setForm({...form, username: e.target.value})}}
// 简写{ }       onChange={(e) => setForm({...form, username: e.target.value})}
